package cz.muni.fi.pa165.travelagency.web;
 
import net.sourceforge.stripes.action.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@UrlBinding("/security/{$event}")
public class SecurityActionBean implements ActionBean {
 
    final static Logger log = LoggerFactory.getLogger(SecurityActionBean.class);
 
    private ActionBeanContext context;
    
    private String name;
    private String password;

    public void setName(String name) {
        this.name = name;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
 
    @DefaultHandler
    public Resolution login() {
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);

        Subject currentUser = SecurityUtils.getSubject();

        try {
            currentUser.login(token);
        } catch (AuthenticationException ae) {
            return new RedirectResolution("/login.jsp");
        }
        if(currentUser.hasRole("admin")){
            return new RedirectResolution(AdminActionBean.class);
        }
        else{
            return new RedirectResolution("/index.jsp");
        }
    }
    
    public Resolution logout() {
        SecurityUtils.getSubject().logout();
        return new RedirectResolution("/index.jsp");
    }    
   
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }
 
    @Override
    public ActionBeanContext getContext() {
        return context;
    }
}